package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.mapper.UserInfoMapper;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private Client smsClient;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Override
    public void senSms(String phone) throws Exception {
        //定义一个key存放带redis中,当作取的key
        String key = "app:sms:"+phone;
        //判断redis中是否有这个key
        Boolean b = redisTemplate.hasKey(key);
//        如果有这个key就抛出异常
        if(b){
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
//        如果没有就创建一个短信验证码
        Random rd = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int i1 = rd.nextInt(10);
            sb.append(i1);
        }
        String value = sb.toString();
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        sendSmsRequest.setPhoneNumbers(phone);
        sendSmsRequest.setTemplateCode("SMS_154950909");
        sendSmsRequest.setTemplateParam("{\"code\":\"" + value + "\"}\n");
        sendSmsRequest.setSignName("阿里云短信测试");
        smsClient.sendSms(sendSmsRequest);
        System.out.println(key);
        System.out.println(value);
        redisTemplate.opsForValue().set(key,value,60, TimeUnit.SECONDS);
    }

    @Override
    public String login(LoginVo loginVo) {
//        从用户表中
        LambdaQueryWrapper<UserInfo> userInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userInfoLambdaQueryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoMapper.selectOne(userInfoLambdaQueryWrapper);
//        如果存在.就检验验证码是否正确
        if(ObjectUtils.isEmpty(userInfo)){
//            如果不正确,就将其添加到数据库中,并返回token
            UserInfo userInfo1 = new UserInfo();
            userInfo1.setPhone(loginVo.getPhone());
            userInfo1.setStatus(BaseStatus.ENABLE);
            String nick_name = "用户:"+loginVo.getPhone();
            userInfo1.setNickname(nick_name);
//            mybatis-plus有主键回显功能
            int inserted = userInfoMapper.insert(userInfo1);
            String token = JwtUtil.createToken(Long.parseLong(inserted + ""), nick_name);
            return token;
        }
//        如果用户的状态码是禁用的,就直接报错
        if(userInfo.getStatus()==BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        System.out.println("app:sms"+loginVo.getPhone());
        String value = (String) redisTemplate.opsForValue().get("app:sms:"+loginVo.getPhone());
        System.out.println(value);
        if(ObjectUtils.isEmpty(value)){
//            如果值为空,就表示验证码已经过期,爆错
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        if(!value.equalsIgnoreCase(loginVo.getCode())){
//            如果值不相等,就标识验证码输入错误
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        String token = JwtUtil.createToken(userInfo.getId(), userInfo.getNickname());
        return token;
    }
}
